import React, { Component } from 'react';
import { Card, Table, Button, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import {
  findCategoryByIdRequest,
  addCategoryRequest,
  updateCategoryRequest,
} from '../../../api/index';
import './category-manage.css';
import UpdateForm from './update-form';
import AddForm from './add-form';

export default class categoryManage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      categories: [],
      parentId: 0,
      parentName: '',
      subCategories: [],
      isAddCategoryShow: false,
      isUpdateCategoryShow: false,
      isLoading: true,
    };
    this.initColumns();
    this.getCategories();
  }

  componentDidMount() {
    this.setState({ isLoading: false });
  }

  showSubCategories = (category) => {
    if (category) {
      this.setState(
        {
          parentId: category.id,
          parentName: category.name,
        },
        () => {
          this.getCategories();
        }
      );
    } else {
      this.getCategories();
    }
  };

  showCategories = () => {
    this.setState(
      {
        parentId: 0,
        parentName: '',
        subCategories: [],
        isLoading: true,
      },
      () => {
        this.getCategories();
      }
    );
  };

  getCategories = async () => {
    const parentId = this.state.parentId;
    const result = await findCategoryByIdRequest(parentId);
    const categories = result.data;
    if (result.status === 0) {
      if (parentId === 0) {
        this.setState({ categories });
      } else {
        this.setState({ subCategories: categories });
      }
    }
  };

  initColumns = () => {
    this.columns = [
      {
        title: '分类名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        width: 350,
        render: (category) => (
          <span>
            <Button onClick={() => this.showUpdateModal(category)} type="link">
              修改分类
            </Button>
            {this.state.parentId === 0 ? (
              <Button
                className="showSub"
                onClick={() => this.showSubCategories(category)}
                type="link"
              >
                查看子分类
              </Button>
            ) : null}
          </span>
        ),
      },
    ];
  };

  showAddModal = () => {
    this.setState({ isAddCategoryShow: true });
  };

  showUpdateModal = (category) => {
    this.category = category;
    this.setState({ isUpdateCategoryShow: true });
  };

  cancelAddModal = () => {
    this.addForm.resetFields();
    this.setState({ isAddCategoryShow: false });
  };

  cancelUpdateModal = () => {
    this.updateForm.resetFields();
    this.category = null;
    this.setState({ isUpdateCategoryShow: false });
  };

  okAddModal = async () => {
    const form = this.addForm;
    if (form) {
      console.log(form.getFieldValue());
      const tempCategory = {
        name: form.getFieldValue().categoryName,
        parentId: form.getFieldValue().selectedCategory,
      };
      console.log(tempCategory);
      const result = await addCategoryRequest(tempCategory);
      console.log(result);
      if (result.status === 0) {
        message.success('添加分类成功！');
        this.setState({ isAddCategoryShow: false }, () => {
          if (this.state.parentId === 0) {
            this.showCategories();
          } else {
            this.showSubCategories();
          }
        });
      }
      this.addForm.resetFields();
    }
  };

  okUpdateModal = async () => {
    const form = this.updateForm;
    if (form) {
      const tempCategory = {
        id: this.category.id,
        name: form.getFieldValue().categoryName,
      };
      const result = await updateCategoryRequest(tempCategory);
      if (result.status === 0) {
        message.success('修改分类成功！');
        this.setState({ isUpdateCategoryShow: false }, () => {
          if (this.state.parentId === 0) {
            this.showCategories();
          } else {
            this.showSubCategories(this.category);
          }
        });
      }
      this.updateForm.resetFields();
      this.category = null;
    }
  };

  render() {
    const title =
      this.state.parentId === 0 ? (
        '一级分类列表'
      ) : (
        <span>
          <Button className="title" onClick={this.showCategories} type="link">
            一级分类列表
          </Button>
          <span>/{this.state.parentName}</span>
        </span>
      );
    const extra = (
      <Button
        onClick={this.showAddModal}
        icon={<PlusOutlined />}
        type="primary"
      >
        添加
      </Button>
    );
    const categoryName = this.category ? this.category : {};

    return (
      <div className="category-container">
        <Modal
          title="添加分类"
          visible={this.state.isAddCategoryShow}
          onOk={this.okAddModal}
          onCancel={this.cancelAddModal}
        >
          <AddForm
            getForm={(form) => {
              this.addForm = form;
            }}
            categories={this.state.categories}
          />
        </Modal>

        <Modal
          title="修改分类"
          visible={this.state.isUpdateCategoryShow}
          onOk={this.okUpdateModal}
          onCancel={this.cancelUpdateModal}
        >
          <UpdateForm
            getForm={(form) => {
              this.updateForm = form;
            }}
            categoryName={categoryName.name}
          />
        </Modal>

        <Card title={title} extra={extra}>
          <Table
            className="category"
            bordered={true}
            dataSource={
              this.state.parentId === 0
                ? this.state.categories
                : this.state.subCategories
            }
            rowKey="id"
            columns={this.columns}
            pagination={{
              defaultPageSize: 6,
              showQuickJumper: true,
              showSizeChanger: false,
            }}
            isLoading={this.state.loading}
          />
        </Card>
      </div>
    );
  }
}
